﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Dal.NSDalCommon;
using Ninject.Core;
using Hotnet.Entity;
using Hotnet.Entity.Search;
using Hotnet.Entity.Enum;

namespace Hotnet.Biz.NSBizCommon
{
	public class BizTag:BaseBiz<Tag>
	{
		private static DalTag db = new DalTag();
		public BizTag() : base(db) { }
		private static List<int> nullList = new List<int>();

		public Tag[] List(int pageNo, int pageSize, out int totalCount, SearchTagCondition searchObj)
		{
			return db.List(pageNo, pageSize, out totalCount, searchObj);
		}

		/// <summary>
		/// 保存多个tag,tag之间用" "分隔
		/// </summary>
		/// <param name="tags"></param>
		/// <returns></returns>
		public List<int> Save(string tags,EnumTagType tagType)
		{
			if (string.IsNullOrEmpty(tags))
				return nullList;
			List<int> tagIDs = new List<int>();
			string[] tagArray = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string tag in tagArray)
			{
				Tag tagInDb=db.GetBy(x => x.TagName.Equals(tag) && x.TargetType == (int)tagType);
				if (tagInDb != null)
				{
					tagIDs.Add(tagInDb.TagID);
					continue;
				}
				tagInDb = new Tag();
				tagInDb.TargetType = (int)tagType;
				tagInDb.TagName = tag;
				tagInDb.AddTime = DateTime.Now;
				db.Insert(tagInDb);
				tagIDs.Add(tagInDb.TagID);
			}
			//tag的引用次数+1
			db.UpdateTagsReferenceCount(tagIDs.ToArray(), EnumTagType.视频);

			return tagIDs;
		}

		public List<int> GetTagIds(string tags, EnumTagType tagType)
		{
			if (string.IsNullOrEmpty(tags))
				return nullList;
			string[] tagArray = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (tagArray.Length <= 0) return nullList;
			List<int> tagIDs = new List<int>();
			foreach (string tag in tagArray)
			{
				Tag tagInDb = db.GetBy(x => x.TagName == tag && x.TargetType == (int)tagType);
				if (tagInDb != null)
				{
					tagIDs.Add(tagInDb.TagID);
				}
			}
			return tagIDs;
		}

		/// <summary>
		/// 列出热门点击Tag
		/// </summary>
		/// <param name="number"></param>
		/// <param name="tagType"></param>
		/// <returns></returns>
		public Tag[] ListClickHotTag(int number,EnumTagType tagType)
		{
			return db.ListClickHotTags(number, tagType);
		}

		/// <summary>
		/// 列出热门引用的Tag
		/// </summary>
		/// <param name="number"></param>
		/// <param name="tagType"></param>
		/// <returns></returns>
		public Tag[] ListReferenceHotTag(int number, EnumTagType tagType)
		{
			return db.ListReferenceHotTag(number, tagType);
		}

		public void UpdateTagsClickCount(int[] tagIDs, EnumTagType tagType)
		{
			if (tagIDs == null || tagIDs.Length == 0)
				return;
			db.UpdateTagsClickCount(tagIDs, EnumTagType.视频);
		}


	}
}
